<?php

namespace app\shop\job\trade;

use sheep\exception\SheepException;
use sheep\job\BaseJob;
use think\queue\Job;
use think\facade\Log;
use think\Collection;
use app\shop\model\trade\Order;

/**
 * 订单自动操作
 */
class OrderAutoOper extends BaseJob
{

    /**
     * 订单自动关闭
     */
    public function autoClose(Job $job, $data)
    {
        try {
            $order = $data['order'];

            // 重新查询订单
            $order = Order::unpaid()->find($order['id']);

            if ($order) {
                \think\facade\Db::transaction(function () use ($order, $data) {
                    // 执行关闭
                    $order->status = Order::STATUS_CLOSED;
                    $order->ext = array_merge($order->ext, ['closed_time' => time()]);      // 取消时间
                    $order->save();
                });
            }

            // 删除 job
            $job->delete();
        } catch (SheepException $e) {
            // 自定义异常时删除 队列
            $job->delete();
            format_log_error($e, 'TradeOrderAutoOper.autoClose.sheepException', '交易订单自动关闭队列');
        } catch (\Exception $e) {
            // 队列执行失败
            format_log_error($e, 'TradeOrderAutoOper.autoClose', '交易订单自动关闭队列');
        }
    }
}
